﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Fashion_API;

namespace Fashion.BackEnd.Common
{
    public partial class UsrMenuLeft : System.Web.UI.UserControl
    {
        private List<BackEndMenu> backEndMenus;
        private List<BackEndPage> backEndPages;
        protected void Page_Load(object sender, EventArgs e)
        {
            DALDataContext d = new DALDataContext();
            backEndPages = d.BackEndPages.ToList();
            backEndMenus = d.BackEndMenus.ToList();
            if (!IsPostBack)
            {
                BindData();
            }
        }

        private void BindData()
        {
            dlMenu.DataSource = backEndMenus.Where(i => i.ParentId == null && i.IsActive).OrderBy(i => i.OrderDisplay);
            dlMenu.DataBind();
        }

        protected void dlMenu_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataList dlMenuChild = (DataList)e.Item.FindControl("dlMenuChild");
                dlMenuChild.DataSource =
                    backEndMenus.Where(
                        i => i.ParentId == Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "Id")) && i.IsActive).
                        OrderBy(i => i.OrderDisplay);
                dlMenuChild.DataBind();
            }
        }

        protected string GetPage(object menuId)
        {
            string content = string.Empty;
            var result =
                backEndPages.Where(i => i.MenuId == Convert.ToInt32(menuId) && i.IsActive).OrderBy(i => i.OrderDisplay);
            foreach (var backEndPage in result)
            {
                if (backEndPage.PagePath.Equals(Request.Url.AbsolutePath) || backEndPage.BackEndPages.FirstOrDefault(i=>i.PagePath.Equals(Request.Url.AbsolutePath))!=null)
                    content += "<li class='actived'><a href='" + backEndPage.PagePath + "'>" + backEndPage.PageName + "</a></li>";
                else
                    content += "<li><a href='" + backEndPage.PagePath + "'>" + backEndPage.PageName + "</a></li>";
            }
            return content;
        }

        protected string GetDisplay(object id)
        {
            BackEndPage page = backEndPages.FirstOrDefault(i => i.PagePath.Equals(Request.Url.AbsolutePath) && i.BackEndMenu.ParentId == Convert.ToInt32(id));
            if (page == null)
            {
                return "display:none";
            }
            return string.Empty;
        }
    }
}